package xin.i18n.starter;

import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.web.servlet.LocaleResolver;
import xin.i18n.resolver.LangHeaderLocaleResolver;
import xin.i18n.util.LocaleType;

import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * <pre>
 * I18n 配置
 * </pre>
 *
 * @author lixin_ma@outlook.com
 * @version 1.0
 * @since 2019/12/4
 */
@Configuration
@EnableConfigurationProperties(I18nProperties.class)
public class I18nAutoConfiguration {
	
	@Bean
	public MessageSource messageSource(I18nProperties properties) {
		ReloadableResourceBundleMessageSource messageBundle = new ReloadableResourceBundleMessageSource();
		messageBundle.setBasename(properties.getBasename());
		messageBundle.setDefaultEncoding(properties.getDefaultEncoding());
		messageBundle.setConcurrentRefresh(properties.isConcurrentRefresh());
		messageBundle.setUseCodeAsDefaultMessage(properties.isUseCodeAsDefaultMessage());
		messageBundle.setCacheSeconds(properties.getCacheSeconds());
		return messageBundle;
	}
	
	@Bean
	public MessageSourceAccessor getDefaultMessageSourceAccessor(MessageSource messageSource) {
		MessageSourceAccessor accessor = new MessageSourceAccessor(messageSource);
		return accessor;
	}
	
	@Bean(name = "localeResolver")
	public LocaleResolver getLocalResolver(I18nProperties properties) {
		LangHeaderLocaleResolver resolver = new LangHeaderLocaleResolver();
		resolver.setSupportedLocales(Arrays.stream(properties.getSupportedLocales().split(","))
				.map(LocaleType::getValue)
				.collect(Collectors.toList()));
		resolver.setDefaultLocale(LocaleType.getValue((properties.getDefaultLocale())));
		resolver.setHeaderName(properties.getInterceptor().getName());
		return resolver;
	}
}
